package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Flight;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import utils.AirTransportRepositoryManager;

public class ReservationController extends AbstractController {

	private AirTransportRepositoryManager repositoryManager;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String idParam = request.getParameter("flightid");
		String jmbgParam = request.getParameter("jmbg");
		String nameParam = request.getParameter("name");
		String surnameParam = request.getParameter("surname");

		ModelAndView mav = new ModelAndView();

		Flight flight = repositoryManager.getFlightByID(idParam);
		mav.addObject("flight", flight);
		
		if (idParam != null && jmbgParam != null &&
				nameParam != null && surnameParam != null &&
			idParam.length() > 0 && jmbgParam.length() > 0 &&
			nameParam.length() > 0 && surnameParam.length() > 0) {
			
			mav = new ModelAndView("reservation_result");
			
			int returnFlag = repositoryManager.reserve(idParam, jmbgParam, nameParam, surnameParam);
			
			String message = "";
			
			switch (returnFlag) {
				case 0:
					message = "Invalid flight selected";
					break;
				case 1:
					message = "Reservation time expired";
					break;
				case 2:
					message = "No free seats on this flight";
					break;
				case 3:
				case 4:
					message = "Wrong JMBG";
					break;
				case 5:
					message = "The passenger has already reserved seat on this flight";
					break;
				case 6:
					message = "Intersection of flight time";
					break;
				case 7:
					message = "The seat is successfully reserved";
					break;
			}
			
			mav.addObject("flight", flight);
			mav.addObject("passenger", nameParam + " " + surnameParam);
			mav.addObject("message", message);
		}
		
		return mav;
	}

	public AirTransportRepositoryManager getRepositoryManager() {
		return repositoryManager;
	}

	public void setRepositoryManager(AirTransportRepositoryManager repositoryManager) {
		this.repositoryManager = repositoryManager;
	}

	
}
